import axios from "axios"
import qs from "qs"
axios.defaults.timeout = 30000

// 表单序列化
const serialize = (data) => {
  const list = []
  Object.keys(data).forEach((ele) => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join("&")
}
// 请求拦截
axios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("toKen")
    if (token) {
      config.headers["x-access-token"] = token
    }
    if (config.method === "post" && config.headers.serialize) {
      config.data = serialize(config.data)
      delete config.data.serialize
    }

    if (config.method === "get") {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: "repeat" })
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截
// HTTPresponse拦截
axios.interceptors.response.use(
  (res) => {
    const message = res.data.msg
    // 登录失效
    if (status === 401) {
      this.$message.error(message)
      localStorage.removeItem("token")
      this.router.push({ path: "/login" })
      return
    }
    // 接口没有访问权限
    if (status === 402) {
      this.$message.error(message)
      return
    }
    // 路由没有访问权限
    if (status === 403) {
      this.$message.error(message)
      return
    }
    if (status !== 200) {
      this.$message.error(message)
      return Promise.reject(message)
    }
    return res
  },
  (error) => {
    return Promise.reject(error)
  }
)
export default axios
